<template>
  <div class="payment-container">
    <h2>商品详情</h2>
    <div>
      <OrderItem v-for="item in payItem" :key="item.id" :item="item"></OrderItem>
    </div>

    <!-- 收货地址 -->
    <h2>收货地址</h2>
    <div class="address-section">
      <div
        class="address-card"
        :class="{ selected: selectedAddress }"
        @click="selectedAddress = !selectedAddress">
        <p class="address-name">{{ user.name }}</p>
        <p class="address-phone">{{ user.phone }}</p>
        <p class="address-detail">{{ user.address }}</p>
      </div>
    </div>
    <!-- 配送方式 -->
    <div class="shipping-section">
      <hr />
      <h3>配送方式</h3>
      <p>包邮</p>
    </div>

    <!-- 订单总结 -->
    <div class="summary-section">
      <hr />
      <div class="summary-item">
        <span>商品件数</span>
        <span>{{ payItem.length }}</span>
      </div>
      <div class="summary-item">
        <span>商品总价</span>
        <span>{{ allPrice }} 元</span>
      </div>
      <div class="summary-item">
        <span>运费</span>
        <span>0 元</span>
      </div>
      <div class="summary-item total">
        <span>应付总额</span>
        <span>{{ allPrice }} 元</span>
      </div>
      <hr />
    </div>

    <!-- 配送地址和操作按钮 -->
    <div class="actions-section">
      <div class="delivery-address">配送至: {{ selectedAddressText }}</div>
      <div class="action-buttons">
        <button class="btn grey-btn" @click="$router.go(-1)">返回</button>
        <button class="btn orange-btn" @click="placeOrder">立即下单</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import OrderItem from '@/components/OrderItem.vue'
import { ref } from 'vue'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { addOrderInfo, updateMoney } from '@/api/personInfo'
import { useRouter } from 'vue-router'
import { updateGoodsSum } from '@/api/goods'

const router = useRouter()

const userStore = useUserStore()

let user = userStore.getUserInfo()

// 下单商品
const payItem = ref([])

// 选中地址
const selectedAddress = ref(true)

// 总价
const allPrice = ref()

// 获取下单信息
const getAllPayItems = () => {
  payItem.value = JSON.parse(sessionStorage.getItem('payItem'))
  sessionStorage.removeItem('payItem')
}

getAllPayItems()

// 计算总价
const calcAllItem = () => {
  return payItem.value.reduce((sum, item) => item.price * item.num + sum, 0).toFixed(2)
}

allPrice.value = calcAllItem()

// 立即下单
const placeOrder = async () => {
  const flag = payItem.value.every((item) => {
    if (item.sum < item.num) {
      ElMessage.error(`${item.name} 存货不足`)
      return false
    }
    return true
  })
  // 商品存货不足
  if (!flag) {
    return
  }
  // 余额不足
  if (+user.money < allPrice.value) {
    console.log(user.money, allPrice.value)
    ElMessage.error('余额不足')
    return
  }
  // 更新余额
  await updateMoney(user.id, allPrice.value)
  // 更新仓库状态
  user = userStore.getUserInfo()
  localStorage.setItem('user', JSON.stringify(user))
  // 添加订单
  for (let i of payItem.value) {
    // 更新商品数量
    await updateGoodsSum(i['id'], i['num'])
    // 添加订单
    await addOrderInfo({ userId: user.id, goodsId: i['id'], num: i['num'] })
  }
  ElMessage.success('下单成功')
  router.replace('/')
}
</script>

<style scoped>
.payment-container {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
  background-color: #ffffff; /* 添加白色背景 */
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  font-family: Arial, sans-serif;
}
.address-section {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}
.address-card {
  flex: 1;
  border: 1px solid #ccc;
  padding: 15px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  background-color: #f9f9f9; /* 背景颜色 */
}
.address-card:hover,
.address-card.selected {
  border-color: orange;
  color: orange;
  background-color: #fff0e6; /* 背景颜色变化 */
}
.address-card.selected .address-name,
.address-card.selected .address-phone,
.address-card.selected .address-detail {
  color: orange; /* 选中时文字变为橙色 */
}
.address-name {
  font-weight: bold;
  font-size: 1em;
  color: #000; /* 黑色字体 */
}
.address-phone,
.address-detail {
  font-size: 0.9em;
  color: #999; /* 浅灰色字体 */
}
.address-card.selected .edit-address {
  display: block;
}
.edit-address {
  display: none;
  position: absolute;
  bottom: 10px;
  right: 10px;
}
.edit-btn {
  background: none;
  color: red;
  border: none;
  cursor: pointer;
}
.add-new {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.add-btn {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #ccc;
  border: none;
  font-size: 1.5em;
  color: white;
  cursor: pointer;
  outline: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.add-text {
  margin-top: 10px;
  color: #999; /* 浅灰色字体 */
  font-size: 0.9em;
}
.order-section {
  margin-bottom: 20px;
}
.product-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.product-item img {
  width: 60px;
  height: 60px;
  margin-right: 10px;
}
.product-details {
  flex: 1;
}
.shipping-section,
.summary-section {
  margin-bottom: 20px;
}
.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
.total {
  font-weight: bold;
}
.actions-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.delivery-address {
  font-weight: bold;
}
.action-buttons {
  display: flex;
  gap: 10px;
}
.btn {
  padding: 10px 20px;
  border: 1px solid transparent;
  cursor: pointer;
  transition: all 0.3s;
}
.grey-btn {
  border-color: #ccc;
  color: #ccc;
}
.grey-btn:hover {
  color: #333;
  border-color: #333;
}
.orange-btn {
  background-color: orange;
  color: white;
}
.orange-btn:hover {
  background-color: #ff6600;
}
</style>
